package com.codeoss.module.ir.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codeoss.framework.context.UserContext;
import com.codeoss.framework.service.impl.BaseTreeService;
import com.codeoss.module.ir.dao.IrMenuMapper;
import com.codeoss.module.ir.model.IrApplication;
import com.codeoss.module.ir.model.IrMenu;
import com.codeoss.module.ir.service.IIrApplicationService;
import com.codeoss.module.ir.service.IIrMenuService;

@Service
public class IrMenuService extends BaseTreeService<IrMenuMapper, IrMenu> implements IIrMenuService {
	@Autowired
	private IIrApplicationService irApplicationService;
	@Override
	public List<Map<String, Object>> getCanAccessMenuList() {
		// TODO Auto-generated method stub
		UserContext userContext=UserContext.getCurrentUserContext();
		QueryWrapper<IrMenu> query=new QueryWrapper<IrMenu>();
		query.eq("menu_type", "folder");
		query.or();
		query.inSql("id", "(select ir_menu_id from res_rel_role_menu where res_role_id in(select res_role_id from res_rel_user_role where res_user_id="+userContext.getResUserId()+"))");
		query.last("or('"+userContext.getUsername()+"'='admin') order by seq_no asc");
		return listMaps(query);
	}

	@Override
	public List<Map<String, Object>> getCanAccessMenuList(Long applicationId) {
		// TODO Auto-generated method stub
		UserContext userContext=UserContext.getCurrentUserContext();
		IrApplication irApplication=irApplicationService.getById(applicationId);
		QueryWrapper<IrMenu> query=new QueryWrapper<IrMenu>();
		StringBuilder sqlBuilder=new StringBuilder();
		sqlBuilder.append(" where menu_type='folder' or ((");
	    
		sqlBuilder.append("id in (select ir_menu_id from res_rel_role_menu where res_role_id in(select res_role_id from res_rel_user_role where res_user_id="+userContext.getResUserId()+"))");
		sqlBuilder.append(" or '"+userContext.getUsername()+"'='admin') and module_type in(");
		String moduleTypeList[]=irApplication.getModuleTypeList().split(",");
		for(int i=0;i<moduleTypeList.length;i++) {
			if(i>0) {
				sqlBuilder.append(",");
			}
			sqlBuilder.append("'").append(moduleTypeList[i]).append("'");
		}
		sqlBuilder.append("))");
		sqlBuilder.append(" order by seq_no asc");
		query.last(sqlBuilder.toString());
		return listMaps(query);
	}
}